﻿// This is the main Angular JS file
var app = angular.module("app", ["ngRoute", "ngAnimate"]);
//Sets and Removes tokens
app.factory("SessionHandler", function ($window) {
    //Puts token in storage
    var setLoggedInToken = function (token, username) {
        $window.sessionStorage.setItem('token', token);
        $window.sessionStorage.setItem('username', username);
    };
    //Clear the login Token
    var removeLoggedInToken = function () {
        $window.sessionStorage.removeItem('token');
        $window.sessionStorage.removeItem('username');
    };
    return {
        setLoggedInToken: setLoggedInToken,
        removeLoggedInToken: removeLoggedInToken
    };
});
app.factory("LoginService", function ($q, $http, SessionHandler, $location) {
    var processLogin = function (username, password) {
        var deferred = $q.defer();
        $http({
            method: "POST",
            data: 'username=' + username + '&password=' + password + '&grant_type=password',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: '/Token',
            isArray: false
        })
        .success(function (data) {
            SessionHandler.setLoggedInToken(data.access_token, username);
            deferred.resolve();
        })
        .error(function (data, status) {
            SessionHandler.removeLoggedInToken();
            deferred.reject(status);
            alert("Invalid Password.")

        });
        return deferred.promise;
    };
    var processLogout = function () {
        var deferred = $q.defer();
        $http({
            method: "POST",
            url: "/api/Account/Logout"
        })
        .success(function (data, status) {
            SessionHandler.removeLoggedInToken();
            deferred.resolve();
        })
        .error(function (data, status) {
            deferred.reject(status);
        });
        return deferred.promise;
    };
    return {
        processLogin: processLogin,
        processLogout: processLogout
    };
});
//Create Our Interceptor
app.factory("AuthInterceptor", function ($window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.getItem('token')) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.getItem('token');
            }
            return config;
        }

    };
});

app.LogInController = function ($scope, $window, $q, LoginService, $location) {
    $scope.username = $window.sessionStorage.getItem('username');
    $scope.token = $window.sessionStorage.getItem('token');
    $scope.Login = function () {
        LoginService.processLogin($scope.user.username, $scope.user.password)
        .then(
        function () {
            $scope.token = $window.sessionStorage.getItem('token');
            $scope.username = $window.sessionStorage.getItem('username');
            $scope.username = $scope.user.username;
            $scope.user.username = "";
            $scope.user.password = "";
            avgrund.deactivate();
            
        },
        function () {
            $scope.token = status;
        });
    }

    $scope.Logout = function () {
        LoginService.processLogout()
        .then(function () {
            $scope.token = $window.sessionStorage.getItem('token');
            $scope.username = $window.sessionStorage.getItem('username');
            $scope.username = "";
            $location.path("/");
        }, function () {
            alert("Error logging out");
        })
    }
    $scope.Registration = function () {
        avgrund.deactivate();
        $location.path("/UserRegistration");
    }

    $scope.showLogin = function () {
        avgrund.activate();
    }

    

};


//Create config for routes and install interceptor
app.config(function ($routeProvider, $httpProvider) {
    $httpProvider.interceptors.push("AuthInterceptor");
    $routeProvider.when("/",
        {
            templateUrl: "/App/Views/ngMain.html",
            controller: "ngMainController"
        }).when("/UserRegistration",
        {
            templateUrl: "/App/Views/ngUserRegistration.html",
            controller: "ngUserRegistrationController"
        }).when("/Admin",
        {
            templateUrl: "/App/Views/ngAdmin.html",
            controller: "ngAdminController"
        }).when("/ItemDetail/:id",
        {
            templateUrl: "/App/Views/ngItemDetail.html",
            controller: "ngItemDetailController"
        }).when("/ItemHistory",
        {
            templateUrl: "/App/Views/ngItemHistory.html",
            controller: "ngItemHistoryController"
        }).when("/Account",
        {
            templateUrl: "/App/Views/ngUserDetail.html",
            controller: "ngUserDetailController"
        })
});